<?php

// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use think\Db;
use think\Validate;
use app\data\model\ShopGoods;
use app\data\model\ShopCates;
use app\data\model\ShopAttr;
use app\data\model\ShopGoodsAttr;
use app\data\model\ShopSpec;
use app\data\model\ShopSpecAttr;
use app\data\model\ShopGoodsSectionPrice;
use app\data\model\ShopGoodsSpec;
use app\data\model\ShopGoodsImages;

/**
 * 系统商品管理
 * Class Goods
 * @package app\admin\controller
 * @author Anyon <zoujingli@qq.com>
 * @date 2017/02/15 18:12
 */
class Goods extends BasicAdmin
{

    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'ShopGoods';

    /**
     * 商品列表
     */
    public function index()
    {
        $this->title = '商品管理';
        $get = $this->request->get();
        $db = Db::name($this->table)
                ->alias('g')
                ->join('__SHOP_GOODS_IMAGES__ i','i.goods_id=g.id')
                ->join('__SHOP_CATES__ c','c.id=g.model_id')
                ->field('g.*,i.iname,c.cname')
                ->where('i.is_cover',1)
                ->where('g.is_deleted',0)
                ->order('g.id','asc');
        foreach (['title'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        // if (isset($get['date']) && $get['date'] !== '') {
        //     list($start, $end) = explode('-', str_replace(' ', '', $get['date']));
        //     $db->whereBetween('login_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        // }
        return parent::_list($db);
    }

    /**
     * 商品数据操作
     * @return [type] [description]
     */
    public function action_goods_operation()
    {
        $post = $this->request->post();
        if(!empty($post['id'])){
            $title = '编辑';
            $goods = ShopGoods::get($post['id']);
        }else{
            $title = '添加';
            $post['id'] = '';
            $goods = new ShopGoods;
        }
        // 检测商品相关数据
        $post = $this->action_goods_data($post);

        $goods->title           = $post['title'];
        $goods->model_id        = $post['model_id'];
        $goods->shop_id         = $post['shop_id'];
        $goods->content         = $post['content'];
        $goods->stock           = $post['stock'];
        $goods->status          = $post['status'];
        $goods->type            = $post['type'];
        $goods->storeprice      = $post['storeprice'];
        $goods->stock_status    = $post['stock_status'];
        $goods->is_free         = $post['is_free'];
        $goods->wholesaleprice  = $post['wholesaleprice'];
        $goods->marketprice     = $post['marketprice'];
        $goods->sort            = $post['sort'];
        $goods->is_presale      = $post['is_presale'];
        $goods->alias           = $post['alias'];
        $goods->weight          = $post['weight'];
        $goods->sku             = $post['sku'];
        $goods->buy_status      = $post['buy_status'];
        $goods->modify_time     = time();
        $goods->save();

        // 获取自增ID
        $post['id'] = $goods->id;

        if($post['id'] == false){
            $this->error('报错失败，请稍后再试~~~');
        }

        // 商品属性
        $this->action_goods_attr($post['id'],$post['model_id'],$post['attr_'.$post['model_id']]);

        // // 处理商品价格
        if($post['buy_status'] == 1){//区间价格
            $this->action_section_price($post['id'],$post);
        }elseif($post['buy_status'] == 2){//规格价格
             $this->action_spec_price($post['id'],$post);
        }
        // 处理商品图片
        $this->action_goods_image($post['id'],$post);

        $this->success('商品'.$title.'成功','');
    }

    /**
     * 处理商品图片
     * @param  [type] $gid  [商品id]
     * @param  [type] $data [商品图片数据]
     * @return [type]       [description]
     */
    protected function action_goods_image($gid,$data)
    {
        $goods_images = new ShopGoodsImages;   
        // 查询封面图片信息
        $cover = $goods_images->goods_cover($gid);
        if(!empty($cover)){
            if($cover['iname'] !== str_replace(HTTP_HOST,'',$data['iname'])){
                $goods_images->save([
                        'goods_id' => $gid,
                        'iname' => str_replace(HTTP_HOST,'',$data['iname']),
                    ],['goods_id' => $gid,'is_cover' => 1]);
            }
        }else{
            // 插入图片封面
            $goods_images->data([
                    'goods_id' => $gid,
                    'iname' => str_replace(HTTP_HOST,'',$data['iname']),
                    'is_cover' => 1,
                ]);
            $goods_images->save();
        }

        // 获取商品图片
        if(!empty($data['inames'])){
            $list = [];
            $goods_image = $goods_images->goods_images($gid);
            $images = explode('|',$data['inames']);
            foreach ($images as $k => $v) {
                if(!empty($v)){
                    $iname = str_replace(HTTP_HOST,'',$v);
                    if(!empty($goods_image)){
                        foreach ($goods_image as $val) {
                            if($iname !== $val['iname']){
                                $list[$k] = [
                                    'goods_id' => $gid,
                                    'iname' => $iname,
                                    'is_cover' => 0,
                                ];
                            }
                        }
                    }else{
                        $list[$k] = [
                                    'goods_id' => $gid,
                                    'iname' => $iname,
                                    'is_cover' => 0,
                                ];
                    }
                }
            }
           
            if(!empty($list)){
                // 添加数据
                $goods_images->saveAll($list);
            }
        }

    }

    /**
     * 处理商品规格
     * @param  [type] $gid      [商品id]
     * @param  [type] $model_id [模型id]
     * @return [type]           [description]
     */
    public function handle_spec_model($gid,$model_id)
    {
        $spec_str = '';
        $spec_attr = [];
        $spec_content = '';
         // 获取规格
        $shop_spec = new ShopSpec;
        $spec = $shop_spec->all_spec_where($model_id);
        // 获取规格属性
        $shop_spec_attr = new ShopSpecAttr;
       
        // 查询商品规格信息
        $shop_goods_spec = new ShopGoodsSpec;
        $goods_spec = $shop_goods_spec->all_goods_spec($gid);
        
        // 规格头部
        if(!empty($spec)){
            foreach ($spec as $k => $v) {
                $attr = $shop_spec_attr->get_attr($v['id']);
                $spec_attr[$k] = $attr;   
                $spec_str .= '<th class="text-left nowrap">'.$v['spec_name'].'</th>';
            }
        }

        $spec_head = '<tr>'
                        .$spec_str
                        .'<th class="text-left nowrap">价格</th>'
                        .'<th class="text-left nowrap">库存</th>'
                        .'<th class="text-left nowrap">SKU</th>'
                        .'<th class="text-left nowrap">操作</th>'
                    .'</tr>';

        // 规格内容
        if(!empty($goods_spec)){
            // 遍历商品规格
            foreach ($goods_spec as $g) {
                // spec_path转换为数组
                $new_path = explode('_',$g['spec_path']);
                // 初始化字符串
                $spec_content .= '<tr>';
                foreach ($spec_attr as $k => $s) {
                    $content_str = '<option value="">请选择</option>';
                    if($s !== ''){
                        foreach ($s as $c) {
                            $selected = '';
                            foreach ($new_path as $n) {
                                if($c['id'] == $n){
                                    $selected = 'selected';
                                }
                            }
                            $content_str .= "<option ".$selected." value='".$c['id']."'>".$c['spec_attr']."</option>";
                        }
                    }
                    $spec_content .= "<td class='text-left nowrap'>"
                                           ."<select class='layui-select full-width sel-spec' old-id='".$new_path[$k]."' style='display:block'>"
                                               .$content_str
                                            ."</select>"
                                       ."</td>";
                }
                $spec_content .= "<td class='text-left nowrap'>"
                                    ."<input type='text' name='spec_price[".$g['spec_path']."][]' value='".$g['spec_price']."' required='required'  placeholder='请输入价格' class='layui-input spec_price'>"
                               ."</td>"
                               ."<td class='text-left nowrap'>"
                                   ."<input type='text' name='spec_stock[".$g['spec_path']."][]' value='".$g['spec_stock']."' required='required' placeholder='请输入库存' class='layui-input spec_stock'>"
                               ."</td>"
                               ."<td class='text-left nowrap'>"
                                   ."<input type='text' name='spec_sku[".$g['spec_path']."][]' value='".$g['spec_sku']."' placeholder='请输入SKU' class='layui-input spec_sku'>"
                               ."</td>"
                               ."<td class='text-left nowrap'>"
                                   ."<span class='layui-btn del_spec' data-path='".$g['spec_path']."' data-id='".$g['id']."'>删除</span>"
                               ."</td>"
                                ."</tr>";
            }
        }

        return ['spec_head' => $spec_head,'spec_content' => $spec_content];
        
    }

    /**
     * 处理商品规格价格
     * @param  [type] $gid  [商品id]
     * @param  [type] $data [规格价格数据]
     * @return [type]       [description]
     */
    protected function action_spec_price($gid,$data)
    {
        $goods_spec = new ShopGoodsSpec;
        
        $list = [];

        foreach ($data['spec_price'] as $k => $v) {
            $goods_spec_data = $goods_spec->goods_spec($gid,$k);
            if(!empty($goods_spec_data)){
                $goods_spec->save([
                            'goods_id'   => $gid,
                            'spec_price' => $data['spec_price'][$k][0],
                            'spec_stock' => $data['spec_stock'][$k][0],
                            'spec_sku'   => $data['spec_sku'][$k][0],
                            'spec_path'  => $k,
                        ],['id' => $goods_spec_data['id']]);
            }else{
                $list[$k] = [
                        'goods_id'   => $gid,
                        'spec_price' => $data['spec_price'][$k][0],
                        'spec_stock' => $data['spec_stock'][$k][0],
                        'spec_sku'   => $data['spec_sku'][$k][0],
                        'spec_path'  => $k,
                    ];
            }
        }

        if(!empty($list)){
            if(!empty($list)){
                $goods_spec->saveAll($list);
            }
        }
         
    }

    /**
     * 处理商品区间价格
     * @param  [type] $gid  [商品id]
     * @param  [type] $data [区间价格数据]
     * @return [type]       [description]
     */
    protected function action_section_price($gid,$data)
    {
        $section = new ShopGoodsSectionPrice;
        $list = [];
        foreach ($data['number'] as $k => $v) {
            // 自增大于等于50修改数据
            if($k >= 50){
                $section->save([
                        'spec_price' => $gid,
                        'price' => $data['price'][$k][0],
                        'unit_id' => $data['unit_id'][$k][0],
                        'number' => $data['number'][$k][0],
                    ],['id' => $k]);
            }else{//添加数据
                $list[$k] = [
                    'goods_id' => $gid,
                    'price' => $data['price'][$k][0],
                    'unit_id' => $data['unit_id'][$k][0],
                    'number' => $data['number'][$k][0],
                ];
            }
        }
        if(!empty($list)){
            $section->saveAll($list);
        }
    }

    /**
     * 处理商品属性
     * @param  [type] $gid     [商品ID]
     * @param  [type] $model_id[模型ID]
     * @param  [type] $content [属性值]
     * @return [type]          [description]
     */
    protected function action_goods_attr($gid,$model_id,$content)
    {
        $attr = ShopAttr::all(['model_id' => 1]);

        $goods_attr = new ShopGoodsAttr;
    
        foreach ($attr as $k => $v) {
            // 判断传过来的之是否设置
            if(isset($content[$k]) && !empty($content[$k])){
                // 查询该值是否存在商品属性表中
                $attr_data = $goods_attr->goods_attr($gid,$v['id']);
                if(!empty($attr_data)){
                    // 修改原来数据
                    $goods_attr->save([
                        'goods_id' => $gid,
                        'attr_id' => $v['id'],
                        'value' => $content[$k],
                        ],['id' => $attr_data['id']]);
                }else{
                    // 新增数据
                    $list[$k] = [
                        'goods_id' => $gid,
                        'attr_id' => $v['id'],
                        'value' => $content[$k],
                    ];

                }
            }else{
                // 查询该值是否存在商品属性表中
                $attr_data = $goods_attr->goods_attr($gid,$v['id']);
                if(!empty($attr_data)){
                    // 删除原来数据
                    $goods_attr->del($attr_data['id']);
                }
            }
            
        }

        // 批量添加数据
        if(!empty($list)){
            $goods_attr->saveAll($list);
        }
    }

    /**
     * 检测商品相关数据
     * @param  [type] $post [description]
     * @return [type]       [description]
     */
    protected function action_goods_data($post)
    {
        // 数据验证
        $rule = [
            ['model_id','require','请选择商品模型'],
            ['shop_id','require','请选择商家'],
            ['title','require','请输入商品名称'],
            ['iname','require','请选择商品封面图'],
            ['storeprice','require','请输入市场价'],
            ['wholesaleprice','require','请输入批发价'],
            ['weight','require','请输入重量'],
            ['sort','require','请输入排序'],
        ];
        $data = [
            'model_id'           => $post['model_id'],
            'shop_id'           => $post['shop_id'],
            'title'             => $post['title'],
            'iname'             => $post['iname'],
            'storeprice'        => $post['storeprice'],
            'wholesaleprice'    => $post['wholesaleprice'],
            'weight'            => $post['weight'],
            'sort'              => $post['sort'],
        ];

        $validate = new Validate($rule);
        $result   = $validate->check($data);

        if(!$result){
            $this->error($validate->getError());
        }

        // 验证商品名是否存在
        $is_exist_title = Db::name($this->table)
                            ->field('id')
                            ->where('model_id',$post['model_id'])->where('shop_id',$post['shop_id'])->where('type',$post['type'])->where('title',$post['title'])->where('id','<>',$post['id'])
                            ->find();
        if(!empty($is_exist_title)){
            $this->error('该商品名已存在');
        }

        if($post['buy_status'] == 0){
            if(!isset($post['marketprice'])){
                $this->error('请填写商品一口价');
            }
        }elseif($post['buy_status'] == 1){
            if(!isset($post['number']) && empty($post['number'])){
                $this->error('请填写区间数量');
            }

            if(!isset($post['price']) && empty($post['price'])){
                $this->error('请填写区间价格');
            }
        }elseif($post['buy_status'] == 2){
            if(!isset($post['spec_price']) && empty($post['spec_price'])){
                $this->error('请输入规格价格');
            }
            if(!isset($post['spec_stock']) && empty($post['spec_stock'])){
                $this->error('请输入规格库存');
            }
        }

        // 处理商品描述数据
        if(isset($post['content']) && !empty($post['content'])){
            $post['content'] = str_replace(HTTP_HOST,'',$post['content']);
        }

        return $post;
    }

    /**
     * 商品添加
     */
    public function add()
    {
        // 获取商品分类信息
        $menus = parent::get_cates();
        // 获取商品计量单位
        $goods_unit = parent::get_goods_unit();
        // 获取商家信息
        $shop_sellers = parent::get_shop_sellers();

        $this->assign('menus', $menus);
        $this->assign('goods_unit', $goods_unit);
        $this->assign('shop_sellers', $shop_sellers);

        return $this->_form($this->table, 'form');
    }

    /**
     * 商品编辑
     */
    public function edit()
    {
        $gid = $this->request->get('id');
        $vo = ShopGoods::get($gid);
        $section_price = [];
        $spec_price = [];
        // 获取商品分类信息
        $menus = parent::get_cates();
        // 获取商品计量单位
        $goods_unit = parent::get_goods_unit();
        // 获取商家信息
        $shop_sellers = parent::get_shop_sellers();
        // 获取商品修改数据
        $goods_images = ShopGoodsImages::all(['goods_id' => $vo['id']]);

        // 设置封面图
        $cover = '';
        $file_images = '';
        $file_id = '';
        foreach ($goods_images as $k => $v) {
            if($v['is_cover'] == 1){
                $cover = $v['iname'];
                unset($goods_images[$k]);
            }else{
                $file_images .= $v['iname'].'|';
                $file_id .= $v['id'].'|';
            }
        }
        $file_images = rtrim($file_images,'|');
        $file_id = rtrim($file_id,'|');
        if($vo['buy_status'] == 1){
            $section_price = ShopGoodsSectionPrice::all(['goods_id' => $vo['id']]);
        }elseif($vo['buy_status'] == 2){
            $spec_price = $this->handle_spec_model($vo['id'],$vo['model_id']);
        }

        // 获取商品属性
        $gattr = new ShopGoodsAttr;
        $goods_attr = $gattr->all_goods_attr($vo['id']);
        
        // 获取模型属性
        $shop_attr = new ShopAttr;
        $attr = $shop_attr->all_model_attr($vo['model_id']);
        foreach ($attr as $k => $v) {
            if($v['type'] == 2){
                $attr[$k]['a_value'] = json_decode($v['a_value'],true);
            }
        }

        $this->assign('menus', $menus);
        $this->assign('cover', $cover);
        $this->assign('goods_unit', $goods_unit);
        $this->assign('file_id', $file_id);
        $this->assign('file_images', $file_images);
        $this->assign('goods_images', $goods_images);
        $this->assign('attr', $attr);
        $this->assign('goods_attr', $goods_attr);
        $this->assign('shop_sellers', $shop_sellers);
        $this->assign('section_price', $section_price);
        $this->assign('spec_price', $spec_price);
        return $this->_form($this->table, 'form');
    }

   

    /**
     * 删除商品
     */
    public function del()
    {
        if (DataService::update($this->table)) {
            $this->success("商品删除成功！", '');
        }
        $this->error("商品删除失败，请稍候再试！");
    }

    /**
     * 商品下架
     */
    public function forbid()
    {
        if (DataService::update($this->table)) {
            $this->success("商品下架成功！", '');
        }
        $this->error("商品下架失败，请稍候再试！");
    }

    /**
     * 商品禁用
     */
    public function resume()
    {
        if (DataService::update($this->table)) {
            $this->success("商品上架成功！", '');
        }
        $this->error("商品上架失败，请稍候再试！");
    }

    /**
     * ajax获取商品计量单位
     * @return [type] [description]
     */
    public function ajax_goods_unit()
    {
        $data = parent::get_goods_unit();
        return json(['code' => 200,'data' => $data]);
    }

    /**
     * ajax获取商品模型
     * @return [type]        [description]
     */
    public function ajax_get_goodsmodel()
    {
        // 获取数据
        $get = $this->request->get();

        // 获取商品属性模型
        $shopcates = ShopCates::get($get['model_id']);
        $goods_attr = $shopcates->attr()->order('sort','desc')->order('id','asc')->select();
        foreach ($goods_attr as $k => $v) {
            if($v['type'] == 2){
                $goods_attr[$k]['a_value'] = json_decode($v['a_value']);
            }
        }
        // 获取规格
        $shop_spec = new ShopSpec;
        $spec = $shop_spec->all_spec_where($get['model_id']);
      
       return json(['code' => 200 ,'data' => ['attr' => $goods_attr,'spec' => $spec]]);
    }

    /**
     * ajax删除商品规格
     * @return [type] [description]
     */
    public function ajax_del_spec()
    {
        $get = $this->request->get();

        $res = ShopGoodsSpec::destroy($get['id']);

        if($res !== false){
            return json(['code' => 200,'message' => '删除成功']);
        }else{
            return json(['code' => 400,'message' => '删除失败']);
        }
    }

    /**
     * ajax删除商品价格规格
     * @return [type] [description]
     */
    public function ajax_del_section()
    {
        $get = $this->request->get();

        $res = ShopGoodsSectionPrice::destroy($get['id']);

        if($res !== false){
            return json(['code' => 200,'message' => '删除成功']);
        }else{
            return json(['code' => 400,'message' => '删除失败']);
        }
    }

    /**
     * ajax获取规格属性
     * @return [type]        [description]
     */
    public function ajax_get_specattr()
    {
        $get = $this->request->get();
        // 初始化数据
        $spec_attr = [];
        // 获取规格
        $shop_spec = new ShopSpec;
        $spec = $shop_spec->all_spec_where($get['id']);
        // 获取规格属性
        $shop_spec_attr = new ShopSpecAttr;
        foreach ($spec as $k => $v) {
            $attr = $shop_spec_attr->get_attr($v['id']);
            $spec_attr[$k] = $attr;   
        }

        return json(['code' => 200 ,'data' => $spec_attr]);
    }

    /**
     * ajax选择规格属性排序
     * @return [type]        [description]
     */
    public function ajax_spec_attr_sort()
    {
        $get = $this->request->get();

        // 字符串拆分维数组
        $attr = explode('_',$get['path']);
        $path = [];
        foreach ($attr as $k => $v) {
            $spec_id = ShopSpecAttr::get($v);
            $path[$spec_id['spec_id']] = $v;
        }

        ksort($path);
        $new_path = trim(implode('_', $path),'_');
        return json(['code' => 200,'data' => $new_path]);
    }

    /**
     * ajax删除商品图片
     * @return [type] [description]
     */
    public function ajax_goods_image()
    {
        $id = $this->request->get('id');
        $goods_image = ShopGoodsImages::get($id);
        $res = $goods_image->delete();
        if($res !== false){
            return json(['code' => 200,'message' => '删除成功']);
        }else{
            return json(['code' => 400,'message' => '删除失败']);
        }
    }
}
